package com.member.mp.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.member.common.core.domain.R;
import com.member.common.core.page.PageResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.CollectionTypeEnum;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.utils.StringUtils;
import com.member.mp.web.user.SupperController;
import com.member.shop.domain.*;
import com.member.shop.dto.MessageStatDto;
import com.member.shop.service.*;
import com.member.shop.vo.MaterialVo;
import com.member.shop.vo.UserCouponVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.member.common.enums.DeleteEnum.NOT_DELETE;

/**
 * 【消息接口】控制器
 *
 * @author thomas
 * @version 1.0
 * @date Mon Jul 03 22:06:51 CST 2024
 **/
@Api(value = "消息接口", tags = {"消息接口"})
@RestController
@RequestMapping("/wx/message")
@Slf4j
public class MessageController extends SupperController {

    @Resource
    private ISysBizMaterialCategoryService sysBizMaterialCategoryService;

    @Resource
    private ISysBizMaterialService sysBizMaterialService;

    @Resource
    private ISysBizMessageService messageService;


    @Resource
    private ISysBizTenantAreaService tenantAreaService;
    @Resource
    private ISysBizProfileService sysBizProfileService;

    /**
     * 获取消息列表
     *
     * @return 获取消息列表
     */
    @GetMapping("/queryMessageList/{messageType}")
    public R<PageResult<SysBizMessage>> queryMessageList(@PathVariable Integer messageType) {


        try {


            startPage();
            LambdaQueryWrapper<SysBizMessage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizMessage::getDeleted, NOT_DELETE.getKey());
            queryWrapper.eq(SysBizMessage::getTenantId, getTenantId());
            queryWrapper.eq(SysBizMessage::getUserId, getUserId());
            if (messageType != null && messageType > 0) {
                queryWrapper.eq(SysBizMessage::getMessageType, messageType);
            }
            List<SysBizMessage> list = messageService.list(queryWrapper);
            TableDataInfo dataTable = getDataTable(list);
            List<?> rows = dataTable.getRows();


            List<SysBizMessage> collect = rows.stream().map(p -> (SysBizMessage) p).collect(Collectors.toList());


            return R.ok(new PageResult<>(dataTable.getTotal(), collect));
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("获取消息列表失败", e);
            return R.fail("获取消息列表失败，请稍后尝试");
        }
    }

    /**
     * 获取消息统计
     *
     * @return 获取消息统计
     */
    @GetMapping("/queryMessageStat")
    public R<List<MessageStatDto>> queryMessageStat() {


        try {


            List<MessageStatDto> list = messageService.getStatListByUserId(getUserId(), getTenantId());


            return R.ok(list);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("获取消息统计列表失败", e);
            return R.fail("获取消息统计列表失败，请稍后尝试");
        }
    }

    /**
     * 删除消息
     *
     * @return 结果
     */
    @PostMapping("/delete/{id}")
    public R<String> delete(@PathVariable Long id) {
        try {

            Long userId = getUserId();


            SysBizMessage byId = messageService.getById(id);


            if (!userId.equals(byId.getUserId())) {
                return R.fail("非法请求");
            }


            LambdaUpdateWrapper<SysBizMessage> updateWrapper = new LambdaUpdateWrapper<>(

            );

            updateWrapper.set(SysBizMessage::getDeleted, 1);
            updateWrapper.set(SysBizMessage::getUpdateTime, new Date());

            updateWrapper.eq(SysBizMessage::getId, id);
            messageService.update(updateWrapper);

            return R.ok();


        } catch (Exception e) {
            e.printStackTrace();

            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    /**
     * 阅读消息
     *
     * @return 结果
     */
    @PostMapping("/read/{id}")
    public R<String> read(@PathVariable Long id) {
        try {

            Long userId = getUserId();

            SysBizMessage byId = messageService.getById(id);


            if (!userId.equals(byId.getUserId())) {
                return R.fail("非法请求");
            }


            LambdaUpdateWrapper<SysBizMessage> updateWrapper = new LambdaUpdateWrapper<>(

            );

            updateWrapper.set(SysBizMessage::getMessageStatus, 1);
            updateWrapper.set(SysBizMessage::getUpdateTime, new Date());
            updateWrapper.set(SysBizMessage::getReadTime, LocalDateTime.now());
            updateWrapper.eq(SysBizMessage::getId, id);
            messageService.update(updateWrapper);

            return R.ok();


        } catch (Exception e) {
            e.printStackTrace();

            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

}
